package Test;

/**
 * 手撕单例
 */
public class SingleInstance {
    /**
     * 饿汉模式
     * 会浪费空间
     */
    private static SingleInstance singleInstance = new SingleInstance();
    public static SingleInstance getInstance(){
        return singleInstance;
    }
}

class LazyManMode{
    /**
     * 懒汉式单例
     * 只是基于单线程的单例模式
     * 多线程就会出问题
     */
    private static SingleInstance singleInstance = null;
    public LazyManMode(){

    }
    public static SingleInstance getSingleInstance(){
        if(singleInstance == null){
            singleInstance = new SingleInstance();
        }
        return singleInstance;
    }
}

class LazyManMode2{
    /**
     * 饿汉单例的多线程（双重检测模式）
     */
    private static volatile SingleInstance singleInstance = null;
    public LazyManMode2(){

    }
    public static SingleInstance getSingleInstance(){
        if(singleInstance == null){
            synchronized (LazyManMode2.class){
                if(singleInstance == null){
                    singleInstance = new SingleInstance();
                }
            }
        }
        return singleInstance;
    }
}
